package com.yyge.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.TimeUnit;

/**
 * 客户端连接的demo 做心跳连接
 */
@SpringBootTest
public class NettyTest01 {
    public static final String HOST = "127.0.0.1";
    public static final int PORT = 1234;
    private static final int READ_TIMEOUT = 10; // 心跳超时时间，单位：秒

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 5, 0, TimeUnit.SECONDS));
                            //向pipeline加入解码器
                            ch.pipeline().addLast("decoder", new StringDecoder());
                            //向pipeline加入编码器
                            ch.pipeline().addLast("encoder", new StringEncoder());
                            ch.pipeline().addLast(new HeartbeatClientHandler());
                        }
                    });

            ChannelFuture channelFuture = b.connect(HOST, PORT).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }

        Thread.sleep(10000);
    }

    static class HeartbeatClientHandler extends SimpleChannelInboundHandler<String> {
        private int heartbeatCount = 0;

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            // 接收到服务端消息的处理逻辑
            System.out.println("[Server]: " + msg);

            // 重置心跳发送计数器
            heartbeatCount = 0;
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleState state = ((IdleStateEvent) evt).state();
                if (state == IdleState.WRITER_IDLE) {
                    // 客户端向服务端发送心跳请求
                    System.out.println("发送心跳请求");
                    ctx.writeAndFlush("heartbeat#" + ++heartbeatCount);
                } else if (state == IdleState.READER_IDLE) {
                    // 超时未接收到服务端应答消息，主动断开连接
                    System.out.println("超时未收到服务端应答消息，断开连接");
                    ctx.channel().close();
                }
            } else {
                super.userEventTriggered(ctx, evt);
            }
        }

    }
}
